package org.rcy.framework.utils.string;

import org.rcy.framework.utils.validate.ValidateUtils;

import java.io.UnsupportedEncodingException;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtils extends org.apache.commons.lang3.StringUtils {

	
	public static final Pattern NO_CHINESE_PATTERRN = Pattern.compile("[^\u4e00-\u9fa5]");

	public static final Pattern NO_BLANK_CONTACT = Pattern.compile("^(852|886|853)(\\d+)$");

	public static String randomString(int length) {
		if(length<1){
			return null;
		}
		String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";     
		Random random = new Random();
		StringBuffer sb = new StringBuffer();     
		for (int i = 0; i < length; i++) {     
		    int number = random.nextInt(base.length());     
		    sb.append(base.charAt(number));     
		}     
		return sb.toString();
	}
	
	/**
	 * 去除空格
	 * @param str
	 * @return
	 */
	public static String removeSpaces(String str){
        while(str.startsWith(" ")){  
        	str= str.substring(1,str.length()).trim();  
         }  
	     while(str.endsWith(" ")){  
	    	 str= str.substring(0,str.length()-1).trim();  
	         }  
	     return str; 
	}

	/**
	 * 判断是否是IP
	 * @param ip
	 * @return
	 */
	public static boolean isIP(String ip){
        boolean b = false;  
        ip = removeSpaces(ip);  
        if(ip.matches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}")){  
            String s[] = ip.split("\\.");  
            if(Integer.parseInt(s[0])<255) {
				if(Integer.parseInt(s[1])<255) {
					if(Integer.parseInt(s[2])<255) {
						if(Integer.parseInt(s[3])<255) {
							b = true;
						}
					}
				}
			}  
        }  
        return b; 
	}
	
	/**
	 * 遮挡电话号码
	 * @param phoneNum
	 * @return
	 */
	public static String shieldPhoneNum(String phoneNum){
		if(isBlank(phoneNum)||phoneNum.length()!=11) {
			return phoneNum;
		}
		
		String beginStr = phoneNum.substring(0,3);
		String endStr = phoneNum.substring(phoneNum.length() - 4, phoneNum.length());
		return beginStr + "****" + endStr;
	}

	/**
	 * 适用公有云脱敏逻辑
	 * 对字符串中间位数用星号遮挡
	 * @param str 需要隐藏的字符串
	 * @param start 前几位（不需要隐藏的）
	 * @param end 后几位（不需要隐藏的,邮箱传0）
	 * @return
	 */
	public static String hiddenMessage4Public(String str, int start, int end) {
		//手机号和email脱敏特殊处理
		if (ValidateUtils.isEmail(str)) {
			return hideEmail(str);
		}
		if (ValidateUtils.isMobile(str)) {
			return hideMobile(str);
		}
		if (str != null && str.length() > start && (start != 0 || end != 0)) {
			String beginStr = str.substring(0, start);
			String endStr = str.substring(str.length() - end);
			if (str.length() > (start + end)) {
				str = beginStr + stars(str.length() - start - end) + endStr;
			}
		}
		return str;
	}

	/**
	 * 非公有云脱敏逻辑
	 * 对字符串中间位数用星号遮挡
	 * @param str 需要隐藏的字符串
	 * @param start 前几位（不需要隐藏的）
	 * @param end 后几位（不需要隐藏的,邮箱传0）
	 * @return
	 */
	public static String hiddenMessage(String str, int start, int end) {
		if (str != null && str.length() > start && (start != 0 || end != 0)) {
			String beginStr = str.substring(0, start);
			String endStr = str.substring(str.length() - end, str.length());
			if (ValidateUtils.isEmail(str)) {
				end = str.length() - str.indexOf("@");
				endStr = str.substring(str.indexOf("@"), str.length());
			}
			if (ValidateUtils.isMobile(str)) {
				if (str.contains(" ")) {
					start = str.split(" ")[0].length() + 1 + start;
					beginStr = str.substring(0, start);
				}
			}
			if (str.length() > (start + end)) {
				str = beginStr + stars(str.length() - start - end) + endStr;
			}
		}
		return str;
	}
    
    /**
     * 长度大于或等于6，保留前2位和后2位，中间*号处理，例如：qy*****ue@163.com
     * 长度大于或等于4小于6，保留前1位和后1位，中间*号处理，例如：q**e@qq.com
     * 长度小于4，保留第1位，其余*号处理，例如：q**@gmaile.com
     * @param email
     * @return
     */
    public static String hideEmail(String email) {
    	if (!ValidateUtils.isEmail(email)) {
    		return email;
    	}
    	int delimiter = email.indexOf("@");
		String firstHalf = email.substring(0, delimiter);
		String secondHalf = email.substring(delimiter);
		int length = firstHalf.length();
	    StringBuilder builder = new StringBuilder();
		if (length > 0 && length < 4) {
			builder.append(firstHalf, 0, 1).append(stars(length - 1)).append(secondHalf);
		} else if (length >= 4 && length < 6){
			builder.append(firstHalf, 0, 1).append(stars(length - 2)).append(firstHalf, length-1, length).append(secondHalf);
		}else if (length >= 6){
			builder.append(firstHalf, 0, 2).append(stars(length - 4)).append(firstHalf, length-2, length).append(secondHalf);
		} else {
			return email;
		}
		return builder.toString();
    }

	/**
	 * 大陆手机号格式：不展示区号，中间4位用*代替
	 *  非大陆手机号格式：展示除区号部分的前3位后两位，其他的用*代替
	 * @param mobile
	 * @return
	 */
	public static String hideMobile(String mobile) {
		if (isBlank(mobile) || !ValidateUtils.isMobile(mobile)) {
			return mobile;
		}
		String beginStr = "";
		String maskStr = "";
		String endStr = "";
		if (ValidateUtils.isCHNMobile(mobile)) {
			beginStr = mobile.substring(0,3);
			endStr = mobile.substring(mobile.length() - 4);
			maskStr = stars(mobile.length() - 7);
		} else {
			String area = "";//带区号的部分
			String noneArea = mobile;//不带区号的部分
			if (mobile.contains(" ")) {
				int blankIndex =  mobile.indexOf(" ");
				area = mobile.substring(0, blankIndex + 1);
				noneArea = mobile.substring(blankIndex + 1);
			}
			beginStr = area + noneArea.substring(0, 3);
			maskStr = stars(noneArea.length() - 5);
			endStr = noneArea.substring(noneArea.length()-2);
		}
		return beginStr + maskStr + endStr;
    }

    /**
     * 隐藏姓名
     * 
     * @param name
     * @return
     */
    public static String hideName(String name) {
    	if (isEmpty(name)) {
    		return "";
    	}
    	if (name.length() <= 3) { // 小于等于3个字，隐藏第一位
    		StringBuilder builder = new StringBuilder();
    		builder.append(stars(1));
    		builder.append(name.substring(1));
    		return builder.toString();
    	} else if (name.length() <= 6) { // 小于等于6个字，仅显示最后2位
    		StringBuilder builder = new StringBuilder();
    		builder.append(stars(name.length() - 2));
    		builder.append(name.substring(name.length() - 2));
    		return builder.toString();
    	} else { // 大于6个字，显示前1后2
    		StringBuilder builder = new StringBuilder();
    		builder.append(name.substring(0, 1));
    		builder.append(stars(name.length() - 3));
    		builder.append(name.substring(name.length() - 2));
    		return builder.toString();
    	}
    }
    
    //获取遮挡的星
  	private static String stars(int num) {
  		StringBuffer stars = new StringBuffer();
  		for(int i=0; i<num; i++){
  			stars.append("*");
  		}
  		return stars.toString();
  	}
  	
  	/**
	 * 处理联系方式 区号 支持（832-9279 4325 、（852）-9279 4325 、+832-9279 4325、832-92794325）
	 * 国内的不加86（国内手机号数据库默认不存区号）
	 * @param contact
	 * @return
	 */
	public static String handleContact(String contact) {
		if (StringUtils.isBlank(contact) || ValidateUtils.isEmail(contact) || ValidateUtils.isMobile(contact)) {
			return contact;
		}
		contact = contact.replace("(", "").replace("+", "").replace(")", "").replace("（", "")
				.replace("）", "").replace(" ", "");
		//非大陆手机号有区号但是没有用空格分开，且没有其他任何特殊字符，则需要分开，例如 886900001111
		Matcher matcher = NO_BLANK_CONTACT.matcher(contact);
		if (matcher.matches()) {
			String area = matcher.group(1);//区号
			String code = matcher.group(2);//号码
			contact = area + " " + code;
		}
		if(!StringUtils.contains(contact,"-")) {
			//没有区号，默认是大陆手机号
			return contact;
		}
		int index = contact.indexOf("-");
		String area = contact.substring(0, index);
		if ("86".equals(area) || "0086".equals(area)) {
			//国内手机号默认不需要区号
			return contact.substring(index + 1, contact.length());
		}
		contact = contact.replace("-", " ");
		return contact;
	}
	
	public static boolean haveBadWord(String str) {
		return false;
	}
	
	
	/**
	 * 判断字符串是否含有Emoji表情
	 **/
	public static boolean containsEmoji(String source) {
		boolean isEmoji = false;
		if(isBlank(source)) {
			return isEmoji;
		}
		int len = source.length();
		for (int i = 0; i < len; i++) {
			char hs = source.charAt(i);
			if (0xd800 <= hs && hs <= 0xdbff) {
				if (source.length() > 1) {
					char ls = source.charAt(i + 1);
					int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
					if (0x1d000 <= uc && uc <= 0x1f77f) {
						return true;
					}
				}
			} else {
				// non surrogate
				if (0x2100 <= hs && hs <= 0x27ff && hs != 0x263b) {
					return true;
				} else if (0x2B05 <= hs && hs <= 0x2b07) {
					return true;
				} else if (0x2934 <= hs && hs <= 0x2935) {
					return true;
				} else if (0x3297 <= hs && hs <= 0x3299) {
					return true;
				} else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50
						|| hs == 0x231a) {
					return true;
				}
				if (!isEmoji && source.length() > 1 && i < source.length() - 1) {
					char ls = source.charAt(i + 1);
					if (ls == 0x20e3) {
						return true;
					}
				}
			}
		}
		return isEmoji;
	}
	
	public static boolean containsUtf8Over3Byte(String source) {
		if (StringUtils.isEmpty(source)) {
			return false;
		}
		boolean hasChar = false;
		try {
			byte[] bytes = source.getBytes("UTF-8");
			for (byte b : bytes) {
				int unsignByte = Byte.toUnsignedInt(b);
				hasChar = unsignByte > 0xef; // 3字节utf8的字节范围是0x00 - 0xef
				if (hasChar) {
					break;
				}
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return hasChar;
	}
	/**
	 * 判断是否是中文名
	 * @param name
	 * @return
	 */
	public static boolean isChineseName(String name) {
		if (StringUtils.isBlank(name)) {
			return true;
		}
		name = name.trim();
		//匹配任意非中文字，匹配到了说明不是全中文
	    Matcher m = NO_CHINESE_PATTERRN.matcher(name);
	    if (m.find()) {
	      return false;
	    }
	    return true;
	}
	
	
	/**
	 * 判断是否全数字
	 * @param str
	 * @return
	 */
	public static boolean isNumberic(String str) {
		if (StringUtils.isBlank(str)) {
			return false;
		}
		return str.matches("\\d+");
	}

	/**
	 * 讲对象转为String字符串
	 * @param b
	 * @param defaultStr 默认值
	 * @return
	 */
	public static String toString(Object b, String defaultStr) {
		if (null == b) {
			return defaultStr;
		} else {
			return b.toString();
		}
	}


}
